package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {


    /***
     * @description 保障项多条件组合
     * @param safeguardVO 保障项
     * @return QueryWrapper查询条件
     */
    @NotNull
    private static LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO) {
        LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
        //保障项编号
        queryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKey()),
                Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey());
        //保障项名称
        queryWrapper.like(!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKeyName()),
                Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName());
        //保障项值
        queryWrapper.eq(!EmptyUtil.isNullOrEmpty(safeguardVO.getDataState()),
                Safeguard::getDataState, safeguardVO.getDataState());
        queryWrapper.orderByDesc(Safeguard::getSortNo);
        return queryWrapper;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE, key = "#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        try {
            //构建分页对象
            Page<Safeguard> SafeguardPage = new Page<>(pageNum, pageSize);
            //构建查询条件
            @NotNull LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //执行分页查询
            Page<SafeguardVO> safeguardVOPage = BeanConv.toPage(
                    page(SafeguardPage, queryWrapper), SafeguardVO.class);
            //返回结果
            return safeguardVOPage;
        } catch (Exception e) {
            log.error("保障项分页查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC, key = "#safeguardId")
    public SafeguardVO findById(String safeguardId) {
        try {
            //执行查询
            return BeanConv.toBean(getById(safeguardId), SafeguardVO.class);
        } catch (Exception e) {
            log.error("保障项单条查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true)},
            put = {@CachePut(value = SafeguardCacheConstant.BASIC, key = "#result.id")})
    public SafeguardVO save(SafeguardVO safeguardVO) {
        try {
            // 转换 SafeguardVO 为 Safeguard
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            if (EmptyUtil.isNullOrEmpty(safeguard.getSafeguardKeyName())) {
                safeguard.setSafeguardKeyName("DefaultKeyName");
            }
            boolean flag = save(safeguard);
            if (!flag) {
                throw new RuntimeException("保存保障项失败");
            }
            //转换返回对象SafeguardVO
            SafeguardVO safeguardVOHandler = BeanConv.toBean(safeguard, SafeguardVO.class);
            return safeguardVOHandler;
        } catch (Exception e) {
            log.error("保存保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, key = "#safeguardVO.id")})
    public Boolean update(SafeguardVO safeguardVO) {
        try {
            //转换SafeguardVO为Safeguard
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            boolean flag = updateById(safeguard);
            if (!flag) {
                throw new RuntimeException("修改保障项失败");
            }
            return flag;
        } catch (Exception e) {
            log.error("修改保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }

    @Override
    @Transactional
    @Caching(evict = {@CacheEvict(value = SafeguardCacheConstant.PAGE, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.LIST, allEntries = true),
            @CacheEvict(value = SafeguardCacheConstant.BASIC, allEntries = true)})
    public Boolean delete(String[] checkedIds) {
        try {
            List<Long> idsLong = Arrays.asList(checkedIds)
                    .stream().map(Long::new).collect(Collectors.toList());
            boolean flag = removeByIds(idsLong);
            if (!flag) {
                throw new RuntimeException("删除保障项失败");
            }
            return flag;
        } catch (Exception e) {
            log.error("删除保障项异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST, key = "#safeguardVO.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            List<Safeguard> list = list(queryWrapper);
            if (!EmptyUtil.isNullOrEmpty(list)) {
                return BeanConv.toBeanList(list, SafeguardVO.class);
            }
        } catch (Exception e) {
            log.error("查询保障项列表失败；{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
        return List.of();
    }


    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST, key = "#safeguardKeyList.hashCode()")
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        try {
            //构建查询条件
            LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Safeguard::getSafeguardKey, safeguardKeyList);
            queryWrapper.eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0);
            //执行列表查询
            List<SafeguardVO> safeguardVOs = BeanConv.toBeanList(list(queryWrapper), SafeguardVO.class);
            return safeguardVOs;
        } catch (Exception e) {
            log.error("保障项列表查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.LIST_FAIL);
        }
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC, key = "#safeguardKey")
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        try {
            //构建查询条件
            LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Safeguard::getSafeguardKey, safeguardKey);
            queryWrapper.eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0);
            //执行列表查询
            return BeanConv.toBean(getOne(queryWrapper), SafeguardVO.class);
        } catch (Exception e) {
            log.error("保障项列表查询异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.FIND_ONE_FAIL);
        }
    }
}
